﻿<cfscript>

/** 
* CAS Frameworks - Ticket-Granting Cookie
*
* @displayname "public.service.ticket.grantingCookie" 
* @hint "CAS Protocol 3.6. ticket-granting cookie" 
* 
* @Output false
* 
* @accessors true
*/

component {
	
	property name="Digest" hint="加密组件";
	property name="Guest" hint="客户端变量组件";
	property name="Secure" hint="安全组件";

	property type="string" name="AppId" hint="使用会话的应用程序名";
	property type="string" name="Domain" hint="会话的作用域";
	property type="string" name="Path" hint="会话的作用路径";
	property type="boolean" name="RequireSSL" hint="仅在 SSL 加密状态下设置 Cookie";
	
	/**
	* @hint "初始化对象"
	* 
	* @Output false
	* 
	* @appId "使用会话的应用程序名"
	* @domainName "会话的作用域"
	* @domainPath "会话的作用路径"
	*/
	public function init( string appId="", string domainName="", string domainPath="", boolean requireSSL=false ) {
		
		var targetApp = arguments.appId;
		var targetDomain = arguments.domainName;
		var targetPath = arguments.domainPath;
		
		if ( targetApp eq "" ) {
			targetApp = "CAS";
		}
		
		if ( targetDomain eq "" ) {
			targetDomain = right( CGI.HTTP_HOST, len(CGI.HTTP_HOST)-find(".", CGI.HTTP_HOST) + 1 );
		}
		
		if ( targetPath eq "" ) {
			targetPath = replace( CGI.SCRIPT_NAME, listLast( CGI.SCRIPT_NAME, "/" ), "", "one" ) ;
		}
		
		setAppId( targetApp );
		setDomain( targetDomain );
		setPath( targetPath );
		
		setRequireSSL( arguments.requireSSL );

		return this;
	}
	
	/**
	* @hint "创建新的 Ticket-Granting Cookie"
	* 
	* @Output false
	* 
	* @ticketId "单点认证的用户认证凭证"
	*/
	public void function create( required string ticketId ) {
		
		var guest = getGuest();
		var digest = getDigest();
		var secure = getSecure();
		
		guest.create( 
						name=getAppId(), 
						domain=getDomain(), path=getPath(), 
						secure=getRequireSSL(), httponly=true, 
						value="TGC-" & digest.encryptString( arguments.ticketId, secure.getIP() )
						);
		
	}

	/**
	* @hint "从指定的 TGC-ID 读取认证信息, 并返回已认证用户名"
	* 
	* @Output false
	*/
	public string function read() {
		
		var digest = getDigest();
		var secure = getSecure();
		
		if ( structKeyExists( cookie, getAppId() ) and left( cookie[getAppId()], 4 ) eq "TGC-" ) {
			
			var ticketId = digest.decryptString( right( cookie[getAppId()], len(cookie[getAppId()])-4 ), secure.getIP() );
			
			return ticketId;
		}
		
		return "";
		
	}
	
	/**
	* @hint "验证当前 TGC-ID 是否在系统注册"
	* 
	* @Output false
	* 
	*/
	public boolean function exists() {
		
		var ticketId = read();
		
		return len(ticketId);
	}
	
	/**
	* @hint "删除 Ticket-Granting Cookie"
	* 
	* @Output false
	*/
	public void function delete() {
		
		var guest = getGuest();
		
		guest.expires(
						name=getAppId(), 
						domain=getDomain(), path=getPath()
						);
		
	}

}

</cfscript>